package com.neutech.controller;

import com.google.gson.Gson;
import com.neutech.entity.User;
import com.neutech.service.CartService;
import com.neutech.service.impl.CartServiceImpl;
import com.neutech.util.NumberUtils;
import com.neutech.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/cart/add")

public class CartAddServlet extends HttpServlet {

    private CartService cartService = new CartServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收请求参数
        String foodIdStr = req.getParameter("foodId");
        String quantityStr = req.getParameter("quantity");

        PrintWriter out = resp.getWriter();
        Gson gson = new Gson();
        //参数格式的校验交给controller来做
        System.out.println(foodIdStr);
        if (foodIdStr == null) {
            out.print(gson.toJson(ResultVO.error(1003, "食品id不能为空")));
            out.close();
            return;
        }
        if (!NumberUtils.isNumeric(foodIdStr)) {
            out.print(gson.toJson(ResultVO.error(1003, "食品id必须是数字")));
            out.close();
            return;
        }
        if (quantityStr == null) {
            out.print(gson.toJson(ResultVO.error(1003, "个数不能为空")));
            out.close();
            return;
        }
        if (!NumberUtils.isNumeric(quantityStr)) {
            out.print(gson.toJson(ResultVO.error(1003, "个数必须是数字")));
            out.close();
            return;
        }

        User user = (User) req.getSession().getAttribute("user");

        //校验通过，交给业务层
        out.print(gson.toJson(cartService.add(Integer.parseInt(foodIdStr),
                Integer.parseInt(quantityStr), user.getId())));
        out.close();
    }
}
